﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SiGeSIB.Data.Security;
using SiGeSIB.GUI.Common;
using SiGeSIB.Data.Common;

namespace SiGeSIB.GUI.Security
{
#if DESIGN
    public partial class UEditConnection : FormRedirector.UEditConnection
#else
	public partial class UEditConnection : FGenericEditor<ConnectionSchema>
#endif
    {
		public UEditConnection()
			: this(null) { }
        public UEditConnection(ConnectionSchema connection)
			: base(connection != null ? EFormState.View : EFormState.Edit, connection != null ? connection.Id : -1)
        {
            InitializeComponent();
			
			EditedItem = _InitialItem = connection;
			FieldsToLock = new List<object>() 
				{
					txtConnectionName,
					txtDatabaseName, 
					txtLogin,
					txtPassword,
					txtServerIP,
					lblConnectionName,
					lblDatabaseName,
					lblLogin,
					lblPassword,
					lblServerIP,
					chkDefault
				};
        }

		#region Attributes
		private ConnectionSchema _InitialItem = null;
		#endregion

		#region Properties
		public ConnectionSchema EditedItem { get; set; }

		protected override bool HasEditPermission
		{
			get
			{
				return
					true;
			}
		}
		#endregion

        #region Overridens
        #region Loading
        protected override ConnectionSchema _LoadEntity(int id)
        {
            return ConfigurationManager.Instance.Connections.GetSchema(id);
        }

        protected override void _FillEntity(ConnectionSchema entity)
        {
            if (entity != null)
            {
                txtConnectionName.Text = entity.ConnectionName;
                txtDatabaseName.Text = entity.DatabaseName;
                txtServerIP.Text = entity.DataSource;
                txtLogin.Text = entity.Login;
                txtPassword.Text = entity.Password;
                chkDefault.Checked = entity.IsDefaultConnection;
            }
        }
        #endregion

        #region Commit
        protected override ConnectionSchema _BuildEntity()
        {
            ConnectionSchema connection = EditedItem = new ConnectionSchema(txtConnectionName.Text, txtLogin.Text, txtPassword.Text, txtServerIP.Text, txtDatabaseName.Text, chkDefault.Checked) { Id = _InitialItem != null ? _InitialItem.Id : -1 };

            return connection;
        }

        protected override ExceptionsContainer _ValidateEntity(ConnectionSchema entity)
        {
            return null;
        } 

		protected override int _SaveEntity(ConnectionSchema entity)
		{
			entity.TestConnection();


			int id = ConfigurationManager.Instance.SaveSchema(entity);
			EditedItem = entity;
			
			return EditedItem.Id = id;
		}
        #endregion
        #endregion
    }
}
